import { ref } from "vue";
import { useRouter, useRoute } from "vue-router";
import { DateRangeFieldNames, useLazyLable } from "@/hooks/useLazyLable";
import useGlobalStore from "@/stores/global.store";
import { storeToRefs } from "pinia";
import { message } from "ant-design-vue";

export default function useComapnyTreeLazyTable(
    service: any,
    otherResetSearchObj?: (...args: any) => void,
    immediate = true,
    statusIsOnly = true,
    dateRangeFieldNames: DateRangeFieldNames = {
        startTime: "startTime",
        endTime: "endTime",
    },
) {
    const pageLoading = ref(false);
    const isShowCompanyInfo = ref(false);
    const hdlSelectCompany = (selectedKeys: any[], e: any) => {
        if (e && e.node) {
            searchObj.value["orgName"] = e.node.title;
        }
        if (selectedKeys.length > 0) {
            searchObj.value["orgId"] = selectedKeys[0];
            hdlResetSearchObj();
            isShowCompanyInfo.value = true;
        } else {
            isShowCompanyInfo.value = false;
        }
    };
    const router = useRouter();
    const route = useRoute();
    const lazyTableStore = useLazyLable(
        router,
        route,
        service,
        {},
        "object",
        immediate,
        dateRangeFieldNames,
    );
    const {
        lazyTable,
        searchObj,
        changePageIndex,
        changePageItems,
        search,
        remove,
        refresh,
        getPopupContainer,
        resetSearchObj,
        presets,
        filterColums,
        dateRange,
        initDateRange,
        hdlCancelChangeStatus,
    } = lazyTableStore;

    const globalStore = useGlobalStore();
    const { userInfo } = storeToRefs(globalStore);
    const noAdmin = () => {
        if (!userInfo.value?.beSuperAdmin) {
            isShowCompanyInfo.value = true;
        }
    };

    const selectedCompanyKeys = ref();
    const expandedKeys = ref();

    const postCompanyListCallBack = async (orgs: any) => {
        const query = route.query;
        if (query.orgId) {
            selectedCompanyKeys.value = [Number(query.orgId)];
            expandedKeys.value = [Number(query.orgId)];
            isShowCompanyInfo.value = true;
        }
    };

    const hdlChangeStatus = async (
        id: any,
        chekced: any,
        field: string = "status",
        vals: any[] = [true, false],
        isOnly = statusIsOnly,
    ) => {
        if (lazyTable.value.loading) {
            return;
        }
        lazyTable.value.loading = true;
        let orgId = selectedCompanyKeys.value
            ? selectedCompanyKeys.value[0]
            : 0;

        try {
            if (chekced == vals[0]) {
                let res = await service.enable(id, orgId, chekced);
            } else {
                let res = await service.disable(id, orgId, chekced);
            }
            message.success("修改状态成功");
            if (isOnly) {
                if (chekced == vals[0]) {
                    lazyTable.value.data.forEach((item) => {
                        if (item.id != id) {
                            item[field] = vals[1];
                        }
                    });
                }
            }
        } catch (err) {
            message.error("修改状态失败");
            refresh();
        } finally {
            lazyTable.value.loading = false;
        }
    };

    const handleTableChange = (
        page: { pageSize: number; current: number },
        filters: any,
        sorter: any,
    ) => {
        if (page.current != lazyTable.value.pagination.current) {
            changePageIndex(page.current);
        } else if (page.pageSize != lazyTable.value.pagination.pageSize) {
            changePageItems(page.pageSize);
        }
    };

    const initSearchParams = () => {
        initDateRange();
    };

    const hdlSearch = () => {
        search();
    };

    const hdlResetSearchObj = (exclude: any = []) => {
        dateRange.value = undefined;
        const cloneSearchValueObj = resetSearchObj();
        const defaultExclude = [
            "orgId",
            "orgName",
            "departmentId",
            "departmentName",
            "t",
        ];

        exclude = Array.isArray(exclude)
            ? [...defaultExclude, ...exclude]
            : defaultExclude;
        exclude.forEach((key: any) => {
            if (cloneSearchValueObj[key]) {
                searchObj.value[key] = cloneSearchValueObj[key];
            }
        });

        otherResetSearchObj &&
            otherResetSearchObj(searchObj, cloneSearchValueObj);
        search();
    };

    return {
        isShowCompanyInfo,
        hdlSelectCompany,
        lazyTable,
        searchObj,
        changePageIndex,
        changePageItems,
        search,
        remove,
        noAdmin,
        selectedCompanyKeys,
        expandedKeys,
        postCompanyListCallBack,
        hdlChangeStatus,
        handleTableChange,
        dateRange,
        initSearchParams,
        hdlSearch,
        hdlResetSearchObj,
        pageLoading,
        getPopupContainer,
        presets,
        filterColums,
        hdlCancelChangeStatus,
    };
}
